import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, Card, Select, Spin, Table, Tag } from 'antd';
import Icon, { SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import hospitalSetApi, { type PageContentListData, PageContentData, PageInfoData, IdictList } from '@/api/hospital/model/hospitalList'
const { Option } = Select;
let flag = false; // 添加一个判断条件，如果为true  那么就是说明我们有筛选条件，false就是直接请求全部数据
export default function HospitalList() {
    // 当前页
    const [page, setPage] = useState(1)
    // 页大小
    const [limit, setLimit] = useState(5)
    // 数据列表
    const [pageList, setPageList] = useState<PageContentListData>([])
    // 数据总数
    const [total, setTotal] = useState(0)
    // 获取表单实例
    const [form] = Form.useForm();
    // console.log(form);
    // 省份列表
    const [economizeList, setEconomizeList] = useState<IdictList>([])
    // 市列表
    const [market, setMarket] = useState<IdictList>([])
    // 区列表
    const [region, setRegion] = useState<IdictList>([])
    // 加载状态
    const [loading, setLoading] = useState(false)

    // 收集医院类型的数据
    const [hospitalType, setHospitalType] = useState<{ hospitalType: string, name: string }[]>([])

    // 获取路由
    const navigate = useNavigate()
    // 定义收集的搜索数据
    const [searchData, setSearchData] = useState<PageInfoData>({
        page: page,
        limit,
        hoscode: '',
        depcode: '',
        hosname: '',
        hostype: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        status: '',
    })
    const columns: ColumnsType<PageContentData> = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: '100px',
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '医院logo',
            dataIndex: 'logoData',
            key: 'logoData',
            align: 'center',
            render: (_, data) => {
                return <img src={`data:image/jpeg;base64,${data.logoData}`} style={{ width: 90 }} alt="" />
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname',
            key: 'hosname',
        },
        {
            title: '等级',
            dataIndex: 'param.hostypeString',
            key: 'param.hostypeString',
            width: '100px',
            render: (_, data) => {
                return <span>{data.param.hostypeString}</span>
            }
        },
        {
            title: '详细地址',
            dataIndex: 'param.fullAddress',
            key: 'param.fullAddress',
            render: (_, data) => {
                return <span>{data.param.fullAddress}</span>
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: '100px',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'tags',
            dataIndex: 'tags',
            render: (_, data) => (
                <div style={{ textAlign: 'center' }}>
                    <Button type='primary'>查看</Button>
                    <Button type='primary' style={{ margin: '0 20px' }} onClick={() => {
                        // console.log(data);
                        navigate(`/syt/hospital/hospitalList/hospitalscheduling/${data.hoscode}`)
                    }}>排班</Button>
                    <Button type='primary' onClick={async () => {
                        // console.log(data.status);
                        await hospitalSetApi.updateStatus({ id: data.id, status: data.status ? 0 : 1 })
                        // 使用当前页去发送数据
                        await getPageList({ page, limit })
                    }}>{`${data.status === 1 ? '下线' : '上线'}`}</Button>
                </div>
            ),
        }
    ];

    // 生命周期s
    useEffect(() => {
        // 挂载
        getPageList({ page, limit })
        getEconomize()
        return () => {

        }
    }, [])

    // 获取分类列表
    async function getPageList({ page, limit }: PageInfoData) {
        // 打开加载
        setLoading(true)
        const data = form.getFieldsValue()
        let res
        if (flag) {
            res = await hospitalSetApi.getPageList({ page, limit, ...data })
        } else {
            res = await hospitalSetApi.getPageList({ page, limit })
        }
        setTotal(res.totalElements)
        setPageList(res.content)
        // 返回出一个医院类型的列表
        let arr = res.content.map(i => {
            return {
                hospitalType: i.hostype,
                name: i.param.hostypeString
            }
        })
        // console.log(arr);
        setHospitalType(arr)
        // 返回数据很之后才关闭
        setLoading(false)
    }
    // 获取省城市数据
    async function getEconomize() {
        const res = await hospitalSetApi.reqProvinceList()
        // console.log(res);
        let arr = res.map((item, index) => {
            return {
                id: item.id,
                name: item.name,
                value: item.value,
                level1: index + '-1'
            }
        });
        setEconomizeList(arr)
    }
    // 获取市
    async function getUrbanArea(parentId: string) {
        // console.log(parentId);
        const res = await hospitalSetApi.reqCityOrDistrictList(parentId)
        setMarket(res)
    }
    // 获取区
    async function getdistinguish(parentId: string) {
        // console.log(parentId);
        const res = await hospitalSetApi.reqCityOrDistrictList(parentId)
        // console.log(res);
        setRegion(res)
    }



    // 点击了表单中具有htmlType='submit'属性的按钮后触发
    const onFinish = (values: any) => {
        flag = true
        // console.log('Success:', values);
        // console.log(form.getFieldsValue());
        getPageList({ page, limit })
        setPage(1)
    };
    // 按钮触发失败后触发
    const onFinishFailed = (errorInfo: any) => {
        // console.log('Failed:', errorInfo);
    };
    // 下拉框的数据
    const onGenderChange = (value: string, option: any) => {
        // console.log(value, option);

    }


    return (
        <Card>
            <Form
                form={form}
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                layout='inline'
                onValuesChange={() => {
                    flag = false
                }}
            >
                <Form.Item
                    name="provinceCode"
                    wrapperCol={{ span: 24 }}
                >
                    <Select
                        placeholder="请选择省"
                        onChange={(code) => {
                            // 改变省的树之后触发发送函数改变市的数据
                            setSearchData({ ...searchData, provinceCode: code })
                            getUrbanArea(code)
                        }}
                        allowClear
                        style={{ minWidth: '195px' }}
                    >
                        {economizeList.map(i => (
                            <Option value={i.value} key={i.id}>{i.name}</Option>
                        ))}


                    </Select>
                </Form.Item>
                <Form.Item
                    name="cityCode"
                    wrapperCol={{ span: 24 }}
                >
                    <Select
                        placeholder="请选择市"
                        onChange={(code) => {
                            getdistinguish(code)
                        }}
                        allowClear
                        style={{ minWidth: '195px' }}
                    >
                        {market.map(i => (
                            <Option value={i.value} key={i.id}>{i.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item
                    name="districtCode"
                    wrapperCol={{ span: 24 }}
                >
                    <Select
                        placeholder="请选择区"
                        onChange={() => { }}
                        allowClear
                        style={{ minWidth: '195px' }}
                    >
                        {region.map(i => (
                            // console.log(i);
                            <Option value={i.value} key={i.id}>{i.name}</Option>
                        ))}


                    </Select>
                </Form.Item>
                <Form.Item
                    name="hosname"
                    wrapperCol={{ span: 24 }}
                >
                    <Input placeholder='医院名称' />
                </Form.Item>
                <Form.Item
                    name="hoscode"
                    wrapperCol={{ span: 24 }}
                >
                    <div>
                        <Input placeholder='医院编码' />
                    </div>
                </Form.Item>
                <Form.Item
                    name="hostype"
                    wrapperCol={{ span: 24 }}
                >
                    <Select
                        placeholder="医院类型"
                        onChange={(code, info) => {
                            getUrbanArea(code)

                        }}
                        allowClear
                        style={{ minWidth: '195px' }}
                    >
                        {hospitalType.map((i, index) => (
                            <Option value={i.hospitalType} key={`${index}+${i.hospitalType}+%`}>{i.name}</Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item
                    name="status"
                    wrapperCol={{ span: 24 }}
                >
                    <Select
                        placeholder="医院状态"
                        onChange={onGenderChange}
                        allowClear
                        style={{ minWidth: '195px' }}
                    >
                        {[0, 1].map(i => (
                            <Option value={i} key={i}>{i}</Option>
                        ))}


                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type='primary' icon={<SearchOutlined />} htmlType='submit'>查询</Button>
                </Form.Item>
                <Form.Item>
                    <Button onClick={() => {
                        // 将默认页变成第一页
                        setPage(1)
                        // 重新获取数据并且是全部数据
                        getPageList({ page: 1, limit: 5 })
                        // 清空表单的值
                        form.resetFields()
                    }}>清空</Button>
                </Form.Item>
            </Form>

            {/* 分页列表 */}

            <Spin spinning={loading} size='large'>
                <Table
                    rowKey={'id'}
                    columns={columns}
                    dataSource={pageList}
                    style={{ margin: '40px 0' }}
                    bordered
                    pagination={{
                        total,
                        pageSize: limit,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: () => `总共:${total}条`,
                        pageSizeOptions: ['3', '5', '10'],
                        onChange: async (page, pageSize) => {
                            // console.log(page, pageSize);
                            // 点击某些页码之后重新获取最新页码和页大小
                            setPage(page)
                            setLimit(pageSize)
                            // 清空上一次的列表数据 否则会报错，因为我们一旦切换了页大小  就是重新发送请求，当前页的大小发生改变  然后总数和数据条数会不想与 会产生警告
                            setPageList([])
                            // 获取结束之后需要重新发送请求 根据最新的数据发送请求
                            await getPageList({ page, limit: pageSize })
                        }
                    }}
                />;
            </Spin>




        </Card >
    )
}
